package cn.csc.module.member.service.menu;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.member.controller.app.menu.vo.AppMemberMenuCreateReqVO;
import cn.csc.module.member.controller.app.menu.vo.AppMemberMenuExportReqVO;
import cn.csc.module.member.controller.app.menu.vo.AppMemberMenuPageReqVO;
import cn.csc.module.member.controller.app.menu.vo.AppMemberMenuUpdateReqVO;
import cn.csc.module.member.convert.menu.MemberMenuConvert;
import cn.csc.module.member.dal.dataobject.menu.MemberMenuDO;
import cn.csc.module.member.dal.mysql.menu.MemberMenuMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.member.enums.ErrorCodeConstants.MENU_NOT_EXISTS;

/**
 * 菜单权限 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
public class MemberMenuServiceImpl implements MemberMenuService {

    @Resource
    private MemberMenuMapper menuMapper;

    @Override
    public BigInteger createMenu(AppMemberMenuCreateReqVO createReqVO) {
        // 插入
        MemberMenuDO menu = MemberMenuConvert.INSTANCE.convert(createReqVO);
        menuMapper.insert(menu);
        // 返回
        return menu.getId();
    }

    @Override
    public void updateMenu(AppMemberMenuUpdateReqVO updateReqVO) {
        // 校验存在
        validateMenuExists(updateReqVO.getId());
        // 更新
        MemberMenuDO updateObj = MemberMenuConvert.INSTANCE.convert(updateReqVO);
        menuMapper.updateById(updateObj);
    }

    @Override
    public void deleteMenu(BigInteger id) {
        // 校验存在
        validateMenuExists(id);
        // 删除
        menuMapper.deleteById(id);
    }

    private void validateMenuExists(BigInteger id) {
        if (menuMapper.selectById(id) == null) {
            throw exception(MENU_NOT_EXISTS);
        }
    }

    @Override
    public MemberMenuDO getMenu(BigInteger id) {
        return menuMapper.selectById(id);
    }

    @Override
    public List<MemberMenuDO> getMenuList(Collection<BigInteger> ids) {
        return menuMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<MemberMenuDO> getMenuPage(AppMemberMenuPageReqVO pageReqVO) {
        return menuMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MemberMenuDO> getMenuList(AppMemberMenuExportReqVO exportReqVO) {
        return menuMapper.selectList(exportReqVO);
    }

}
